package com.tengju.data.infrastructure.schedule;


import com.tengju.data.domain.model.alert.AlertEvent;
import com.tengju.data.domain.model.alert.AlertService;
import com.tengju.data.domain.model.report.SettleEvent;
import com.tengju.data.domain.model.service.AchievementBonusDateConfigService;
import com.tengju.data.domain.shared.CastUtil;
import com.tengju.data.domain.shared.DateUtil;
import com.tengju.data.infrastructure.exception.ScheduleJobException;
import com.tengju.data.infrastructure.persistence.redis.RedisLock;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class SettleMarketBonusJob implements ApplicationContextAware {

    private final AlertService alertService;
    private final RedisLock redisLock;
    private ApplicationContext applicationContext;

    private final String jobName = "月业绩奖励结算任务";

    private final String jobKey = "settleAchievementBonusJob";

    @XxlJob("settleMarketBonusJob")
    public ReturnT<String> execute(String params) {
        String lockToken = null;
        try {
            lockToken = redisLock.tryLock(jobKey, 1000 * 60 * 60);
            if (StringUtils.isBlank(lockToken)) {
                throw new ScheduleJobException("任务正在执行中,稍后再试");
            }
            int month = 0;
            if (StringUtils.isNotBlank(params)) {
                month = CastUtil.castInt(params);
            }
            applicationContext.publishEvent(new SettleEvent(month));
        } catch (Exception e) {
            log.error("{}, jobError",jobName, e);
            AlertEvent event = new AlertEvent(jobName + "异常");
            event.addItem("任务参数",params);
            event.addItem("异常信息",e.getMessage());
            alertService.alert(event);
            return ReturnT.FAIL;
        } finally {
            redisLock.unlock(jobKey,lockToken);
        }
        return ReturnT.SUCCESS;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
